package com.csii.security.authentication.dingtalk;

import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用于校验用户手机号是否允许通过认证
 * @Auther: ian
 */
public class DingTalkAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private boolean postOnly = true;


    public DingTalkAuthenticationFilter() {
        super(new AntPathRequestMatcher("/ding-talk/form", "GET"));
    }

    // ~ Methods
    // ========================================================================================================

    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("GET")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String ddToken = obtainDdToken(request);
        DingTalkAuthenticationToken authRequest = new DingTalkAuthenticationToken(ddToken);


        // sessionID, hostname
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }


    /**
     * 从请求中获取手机号码
     */
    @Nullable
    protected String obtainDdToken(HttpServletRequest request) {
        return request.getParameter("dd_token");
    }

    /**
     * 将 sessionID和hostname添加 到MobileAuthenticationToken
     */
    protected void setDetails(HttpServletRequest request,
                              DingTalkAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}